package com.boarsoft.boar.demo.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.order.service.PocOrderService;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.Util;

@Component("orderServlet")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = -6265432638693407198L;

	private static final Logger log = LoggerFactory.getLogger(OrderServlet.class);

	private static final String JSON_TRUE = "{ \"success\": true }";
	private static final String JSON_FALSE = "{ \"success\": false }";

	@Autowired
	@Qualifier("orderServ")
	protected PocOrderService orderService;

	@Autowired
	@Lazy
	private Cache redisCache;

	// @Autowired
	// private PocOrderBiz pocOrderBiz;

	@Override
	protected void doGet(HttpServletRequest rq, HttpServletResponse rp) throws ServletException, IOException {
		String rs = "ok";
		try {
			PocOrder o = null;
			switch (rq.getServletPath()) {
			case "/find":
				o = orderService.find(//
						Integer.parseInt(rq.getParameter("tenantId")), //
						Integer.parseInt(rq.getParameter("orderId")));
				rs = o.toString();
				break;
			case "/place":
				// 创建订单
				o = new PocOrder();
				o.setStatus(PocOrder.STATUS_PLACE);
				o.setCreateTime(Util.getStdmfDateTime());
				o.setModifyTime(o.getCreateTime());
				o.setUserId(Integer.parseInt(rq.getParameter("userId")));
				o.setTenantId(Integer.parseInt(rq.getParameter("tenantId")));
				o.setProductId(Integer.parseInt(rq.getParameter("productId")));
				o.setProductNum(Integer.parseInt(rq.getParameter("productNum")));
				o.setAmount(Integer.parseInt(rq.getParameter("amount")));
				// 减库存
				long s = redisCache.incr("store", String.valueOf(//
						o.getProductId()), -o.getProductNum());
				if (s < 0) {
					// 还原库存
					s = redisCache.incr("store", String.valueOf(//
							o.getProductId()), +o.getProductNum());
					log.warn("Store of product {} is {}", o.getProductId(), s);
					rs = JSON_FALSE;
				} else {
					// 获取订单号
					long id = redisCache.incr("default", "order_id", 1);
					o.setOrderId((int) id);
					// 生成订单
					rs = orderService.place(o) ? JSON_TRUE : JSON_FALSE;
				}
				break;
			case "/finish":
				o = new PocOrder();
				o.setOrderId(Integer.parseInt(rq.getParameter("orderId")));
				o.setTenantId(Integer.parseInt(rq.getParameter("tenantId")));
				rs = orderService.finish(o, Boolean.parseBoolean(rq.getParameter("callType")))//
						? JSON_TRUE : JSON_FALSE;
				break;
			default:
				rs = "{ \"success\": false, data: \"unknown.path\" }";
				log.error("Unknow path = {}", rq.getServletPath());
			}
		} catch (Exception e) {
			log.error("Error on process request", e);
			rs = e.getMessage();
		}
		rp.getWriter().write(rs);
		rp.flushBuffer();
	}
}
